/*
 * @Author: lokei
 * @Date: 2022-08-31 17:57:29
 * @LastEditors: lokei
 * @LastEditTime: 2022-09-01 09:27:50
 * @Description: 
 */
package cn.lokei.sim.entity;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class Device {
    private String identity;
    private String status;
    private Integer keep_alive;

    MqttConnectOptions mqttConnectOptions;
    MqttClient mqttClient;
    MemoryPersistence memoryPersistence;

    public Device(String identity) {
        this.identity = identity;
        this.keep_alive = 0;
        this.init(this.identity);
    }

    public void heartbeat() {
        if (null != mqttClient) {
            if (!mqttClient.isConnected()) {
                try {
                    log.info("创建连接:" + mqttClient.isConnected());
                    mqttClient.connect(mqttConnectOptions);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
            if(mqttClient.isConnected()) {
                this.publishMessage(this.identity + "_heartbeat", "" + this.keep_alive, 0);
                if(this.keep_alive >= Integer.MAX_VALUE) {
                    this.keep_alive = 0;
                } else {
                    this.keep_alive = this.keep_alive + 1;
                }
            }
        }
    }

    public void init(String clientId) {
        // 初始化连接设置对象
        mqttConnectOptions = new MqttConnectOptions();
        // 初始化MqttClient
        if (null != mqttConnectOptions) {
            // true可以安全地使用内存持久性作为客户端断开连接时清除的所有状态
            mqttConnectOptions.setCleanSession(true);
            // 设置连接超时
            mqttConnectOptions.setConnectionTimeout(30);
            // 设置持久化方式
            memoryPersistence = new MemoryPersistence();
            if (null != memoryPersistence && null != clientId) {
                try {
                    mqttClient = new MqttClient("tcp://175.178.217.142:1883", clientId,
                            memoryPersistence);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            } else {

            }
        }
    }

    public void connect() {
        // 设置连接和回调
        if (null != mqttClient) {
            if (!mqttClient.isConnected()) {
                try {
                    log.info("创建连接:" + mqttClient.isConnected());
                    mqttClient.connect(mqttConnectOptions);
                } catch (MqttException e) {
                    e.printStackTrace();
                }

            }
        } else {
            log.error("mqttClient为空");
        }
    }

    // 关闭连接
    public void closeConnect() {
        // 关闭存储方式
        if (null != memoryPersistence) {
            try {
                memoryPersistence.close();
            } catch (MqttPersistenceException e) {
                e.printStackTrace();
            }
        } else {
            log.error("memoryPersistence is null");
        }

        // 关闭连接
        if (null != mqttClient) {
            if (mqttClient.isConnected()) {
                try {
                    mqttClient.disconnect();
                    mqttClient.close();
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            } else {
                log.error("mqttClient is not connect");
            }
        } else {
            log.error("mqttClient is null");
        }
    }

    // 发布消息
    public void publishMessage(String pubTopic, String message, int qos) {
        if (null != mqttClient && mqttClient.isConnected()) {
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setQos(qos);
            mqttMessage.setPayload(message.getBytes());
            MqttTopic topic = mqttClient.getTopic(pubTopic);
            if (null != topic) {
                try {
                    MqttDeliveryToken publish = topic.publish(mqttMessage);
                    if (!publish.isComplete()) {
                        log.info("消息发布成功");
                    }
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }

        } else {
            reConnect();
        }

    }

    // 重新连接
    public void reConnect() {
        if (null != mqttClient) {
            if (!mqttClient.isConnected()) {
                if (null != mqttConnectOptions) {
                    try {
                        mqttClient.connect(mqttConnectOptions);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                } else {
                    log.error("mqttConnectOptions is null");
                }
            } else {
                log.error("mqttClient is null or connect");
            }
        } else {
            init("admin");
        }

    }

    // 订阅主题
    public void subTopic(String topic) {
        if (null != mqttClient && mqttClient.isConnected()) {
            try {
                mqttClient.subscribe(topic, 1);

            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            log.error("mqttClient is error");
        }
    }

    // 清空主题
    public void cleanTopic(String topic) {
        if (null != mqttClient && !mqttClient.isConnected()) {
            try {
                mqttClient.unsubscribe(topic);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            log.error("mqttClient is error");
        }
    }
}
